package com.yudi.blog.bussiness.controller.admin;

import com.yudi.blog.bussiness.dto.Tag;
import com.yudi.blog.bussiness.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @Author YuDi
 * @Date 2021/11/10 16:23
 * @Version 1.0
 */
@Controller
@RequestMapping("/admin")
public class TagsController {

    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String list(@PageableDefault(size = 5, sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable,
                       Model model){
        model.addAttribute("page", tagService.listTag(pageable));
        return "admin/tags";
    }

    @GetMapping("/tags/input")
    public String add(Model model){

        model.addAttribute("tag", new Tag());

        return "admin/tags-input";
    }



    @PostMapping("/tags")
    public String save(Tag tag, RedirectAttributes redirectAttributes){
        Tag t = tagService.saveTag(tag);

        if(t == null){
            redirectAttributes.addFlashAttribute("message", "标签添加失败");
        } else {
            redirectAttributes.addFlashAttribute("message","标签添加成功");
        }
        return "redirect:/admin/tags";
    }


    @GetMapping("/tags/delete/{id}")
    public String delete(@PathVariable Long id, RedirectAttributes redirectAttributes){

        tagService.deleteTag(id);
        redirectAttributes.addFlashAttribute("message", "标签删除成功");

        return "redirect:/admin/tags";
    }


    @GetMapping("/tags/input/{id}")
    public String editInput(@PathVariable Long id, Model model) {
        model.addAttribute("tag", tagService.getTag(id));
        return "admin/tags-input";
    }

    @PostMapping("/tags/input/{id}")
    public String update(@PathVariable Long id, Tag tag, RedirectAttributes attributes){
        if ("".equals(tag.getName())) {
            return "admin/tags-input";
        }
        Tag t = tagService.updateTag(id,tag);
        if (t == null ) {
            attributes.addFlashAttribute("message", "更新失败");
        } else {
            attributes.addFlashAttribute("message", "更新成功");
        }
        return "redirect:/admin/tags";
    }

}
